package com.xmb.wpclient;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xmb.wpclient.constant.R;
import com.xmb.wpclient.controller.VoucherController;
import com.xmb.wpclient.entity.VoucherUploadRecord;
import com.xmb.wpclient.service.IVoucherUploadRecordService;
import com.xmb.wpclient.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class ScheduledService {

	@Autowired
	private VoucherController voucherController;

	@Autowired
	private IVoucherUploadRecordService iVoucherUploadRecordService;

	ExecutorService service = Executors.newFixedThreadPool(5);

	public static final String cron = "30 12 4 * *";
	
	//每月4号中午12点30执行
	//批次状态数据获取
	@Scheduled(cron=cron)
	public void requestUnitStatus() {
		service.execute(() -> {//改成异步执行后，就算你再耗时也不会印象到后续任务的定时调度了
			String month = DateUtil.getLastMonth();
			try {
				//检查当前月是否已上传
				VoucherUploadRecord uploadRecord = iVoucherUploadRecordService.getOne(new LambdaQueryWrapper<VoucherUploadRecord>()
						.eq(VoucherUploadRecord::getIyear, month.split("-")[0])
						.eq(VoucherUploadRecord::getIperiod, month.split("-")[1]));
				if(uploadRecord == null || !uploadRecord.getStatus()){
					R r = voucherController.upload(month.split("-")[0], month.split("-")[1]);
					if(r.get("code").toString().equals("200")){
						log.info("=======================ScheduleJob：年度："+month.split("-")[0]+"，会计期间："+month.split("-")[1]+"已自动上传成功=======================");
					}else{
						log.error("=======================ScheduleJob：年度："+month.split("-")[0]+"，会计期间："+month.split("-")[1]+"自动上传失败，失败原因："+r.get("msg").toString()+"=======================");
					}
				}else{
					log.info("=======================ScheduleJob：任务已被手动执行成功，自动任务将不再执行=======================");
				}
				log.info("=======================ScheduleJob：执行任务完成=======================");
			} catch (Exception e) {
				e.printStackTrace();
				log.error("=======================ScheduleJob：年度："+month.split("-")[0]+"，会计期间："+month.split("-")[1]+"自动上传失败，"+e.getMessage()+"=======================");
			}
		});
	}
}
